package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.FoodDao;
import com.foreknow.elm.po.Business;
import com.foreknow.elm.po.Food;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class FoodDaoImpl implements FoodDao {
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;
    @Override
    public List<Food> listFoodByBusinessId(int businessId) throws Exception {
        List<Food> list = new ArrayList<>();
        String sql = "SELECT * FROM food WHERE businessId = ? ORDER BY foodId";
        try{
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,businessId);
            //执行查询
            rs = pst.executeQuery();
            //遍历结果集
            while (rs.next()) {
                Food food = new Food();

                food.setFoodId(rs.getInt("foodId"));
                food.setFoodName(rs.getString("foodName"));
                food.setFoodExplain(rs.getString("foodExplain"));
                food.setFoodImg(rs.getString("foodImg"));
                food.setFoodPrice(rs.getDouble("foodPrice"));
                food.setBusinessId(rs.getInt("businessId"));
                food.setRemarks(rs.getString("remarks"));
                //将对象保存到集合中
                list.add(food);
            }
        }finally {                          //这里不能处理异常，也就是没有catch，只有finally
            DBUtil.close(rs,pst);           //这里负责关闭PreparedStatement和ResultSet
        }
        return list;
    }
}
